<?php

namespace Portal\Common\FastRoute;

use PhalApi\FastRoute\Lite as FastRouteLite;
use PhalApi\Translator;
use PhalApi\Request;
use PhalApi\FastRoute\Handler;
use PhalApi\FastRoute\Handler\ErrorHandler;

class Lite extends FastRouteLite
{
    public function dispatch(Handler $errorHandler = null)
    {
        if ($errorHandler === null) {
            $errorHandler = new ErrorHandler();
        }

        //装载配置的自定义路由规则，异常时直接抛出以提示开发同学
        $dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) {
            foreach (\PhalApi\DI()->config->get('adminapp.FastRoute.routes') as $routeCfg) {
                $r->addRoute($routeCfg[0], $routeCfg[1], $routeCfg[2]);
            }
        });

        // Fetch method and URI from somewhere
        $httpMethod = $_SERVER['REQUEST_METHOD'];

        // 获取基准 url
        $base_url = \PhalApi\DI()->config->get('adminapp.FastRoute.base_url');
        // 排除基准 url，取出真实路由
        $reqestUriFixed = substr($_SERVER['REQUEST_URI'], strlen($base_url), strlen($_SERVER['REQUEST_URI']) + 1);

        $uri = urldecode(parse_url($reqestUriFixed, PHP_URL_PATH));
        $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
        switch ($routeInfo[0]) {
            case \FastRoute\Dispatcher::NOT_FOUND:
                // ... 404 Not Found (兼容无路由)
                break;
            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                $response = \PhalApi\DI()->response;
                $response->setRet(405);
                $response->setMsg(\PhalApi\T(
                    'FastRoute Method Not Allowed, It Should be: {methods}',
                    array('methods' => implode('/', $routeInfo[1]))
                ));

                // ... 405 Method Not Allowed (异常处理)
                $errorHandler->excute($response);
                break;
            case \FastRoute\Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars = $routeInfo[2];

                // ... call $handler with $vars (交由PhalApi处理响应)
                $vars['service'] = $handler;

                // 加传更多POST/GET参数
                $_GET = array_merge($_GET, $vars);
                $vars = array_merge(\PhalApi\DI()->request->getAll(), $vars);

                \PhalApi\DI()->request = new Request($vars);
                break;
        }
    }
}
